package cn.zspt.vank.controller;

import cn.zspt.vank.domain.User;
import cn.zspt.vank.domain.dto.LoginUser;
import cn.zspt.vank.exception.LoginException;
import cn.zspt.vank.service.UserService;
import cn.zspt.vank.util.Base64;
import cn.zspt.vank.util.CacheService;
import cn.zspt.vank.util.JwtUtils;
import cn.zspt.vank.util.MD5Utils;
import com.google.code.kaptcha.Producer;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping(value = "/login",produces = "application/json;charset=utf-8")
    @Operation(summary = "登录",description = "携带用户名，密码，验证码")
    public Map<String, Object> login(@RequestBody LoginUser user) throws LoginException {
        //System.out.println(user);
        String redishCode=cacheService.getObject("captcha_codes:" + user.getUuid(),String.class);
        if(!user.getVerifyCode().equals(redishCode)){
            throw new LoginException();
        }
        user.setPassword(MD5Utils.generateEncryp(user.getPassword()));
        User dbUser=userService.login(user);
        //System.out.println(dbUser);
        if(dbUser!=null){
            Map<String, String> tokenmap= new HashMap<>();
            tokenmap.put("username", dbUser.getUsername());
            tokenmap.put("userId", dbUser.getUserId().toString());
            String token= JwtUtils.getToken(tokenmap);
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            dbUser.setPassword("");
            map.put("user", dbUser);
            return map;
        }else{
            throw new LoginException();
        }
    }

    @Resource
    private Producer captchaProducer;
    @Autowired
    private CacheService cacheService;
    @GetMapping("/captchaImage")
    @Operation(summary = "获取验证码")
    public Map<String,Object> getCode() throws IOException {
        // AjaxResult 本质是一个 HashMap, 调用put方法向内放置内容
        Map<String,Object> map = new HashMap<>();
        String uuid = UUID.randomUUID().toString();
        String redis_key = "captcha_codes:" + uuid;
        String captcha_code = captchaProducer.createText();
        //System.out.println(captcha_code);

        BufferedImage image = captchaProducer.createImage(captcha_code);

        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        ImageIO.write(image, "jpg", os);

        cacheService.add("captcha_codes:" + uuid,captcha_code,3, TimeUnit.MINUTES);

        //System.out.println(cacheService.getObject("captcha_codes:" + uuid,String.class));
        map.put("uuid", uuid);
        map.put("img", Base64.encode(os.toByteArray()));
        return map;
    }

}
